package com.service.lotterySystem.controller;

import com.service.config.annotation.Log;
import com.service.config.enums.BusinessType;
import com.service.config.enums.OperatorType;
import com.service.config.utils.*;
import com.service.lotterySystem.dto.AddOperateUserDto;
import com.service.lotterySystem.dto.LoginUserDto;
import com.service.lotterySystem.dto.OperateUserInfoDto;
import com.service.lotterySystem.entity.OperateInfo;
import com.service.lotterySystem.entity.Roles;
import com.service.lotterySystem.enums.RoleTypeEnum;
import com.service.lotterySystem.service.OperateUserService;
import com.service.lotterySystem.service.RolesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

import static com.service.config.constant.Constant.*;

/**
 * @author ：hjl
 * @date ：Created in 2022/01/10 15:48
 * @description：
 */
@RestController
@RequestMapping("operateUserInfo")
@Api(value = "运营管理人员接口", tags = "运营管理人员接口")
public class OperateUserController {
    @Resource
    private OperateUserService operateUserService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private RolesService rolesService;
    /**
     * 统一登录
     *
     * @param
     * @return
     */
    @PostMapping(value = "auth",produces="application/json")
    @ApiOperation(value = "统一登录")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result loginManage(@RequestBody LoginUserDto loginUserDto) throws Exception {
        if(loginUserDto.getAccount() == null || "".equals(loginUserDto.getAccount())
                || "".equals(loginUserDto.getPassword()) || loginUserDto.getPassword() == null){
            return Result.failure(10003,"用户名或密码为空");
        }
        HashMap map = operateUserService.getToken(loginUserDto);
        if(map.isEmpty()){
            return Result.failure(USER_NOT_FOUND,"用户不存在");
        }
        return Result.ok().setData(map);

    }
    /**
     * 新增渠道运营人员
     *
     * @param
     * @return
     */
    @PostMapping(value = "addOperateUser",produces="application/json")
    @ApiOperation(value = "新增渠道运营人员")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result addOperateUser(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                                 @RequestBody AddOperateUserDto addOperateUserDto) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                OperateUserInfoDto userDto = JsonXMLUtils.json2obj(redisUtil.getValue(cloudAuthToken+userId),OperateUserInfoDto.class);
                if (!userDto.getRoleType().equals(RoleTypeEnum.CREATOR.getCode())) {
                    return Result.failure(USER_NO_AUTHORITY,userNoAuthority);
                }
                OperateInfo operateUserInfo = ModelMapperUtil.strictMap(addOperateUserDto, OperateInfo.class);
                operateUserInfo.setRoleDesc(addOperateUserDto.getRoleName());
                operateUserInfo.setOperateId(userId);
                operateUserInfo.setId(IdUtil.getStringId());
                operateUserInfo.setAddTime(new Date());
                operateUserInfo.setAdder(userDto.getOperateName());
                OperateInfo insert = operateUserService.insert(operateUserInfo);
                return Result.ok().setData(insert);
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 生成二维码
     *
     * @param
     * @return
     */
    @GetMapping(value = "addUrlScheme",produces="application/json")
    @ApiOperation(value = "生成二维码")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result addUrlScheme(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                               @RequestParam(value = "ordinary",required = false) @ApiParam("超级管理员为普通管理员生成二维码时传该参数")String ordinary) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                OperateUserInfoDto userDto = JsonXMLUtils.json2obj(redisUtil.getValue(cloudAuthToken+userId),OperateUserInfoDto.class);
                if (!userDto.getRoleType().equals(RoleTypeEnum.CREATOR.getCode())) {
                    return operateUserService.addUrlScheme(userId);
                }
                return operateUserService.addUrlScheme(ordinary);
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 根据姓名查询新增用户
     *
     * @param
     * @return
     */
    @GetMapping(value = "fineOperateUser",produces="application/json")
    @ApiOperation(value = "根据姓名查询新增用户/查询已经创建的渠道运营账号")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result fineOperateUser(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                                 @RequestParam(value = "name",required = false) @ApiParam("根据name模糊查询") String name,
                                  @RequestParam(value = "region",required = false) @ApiParam("根据region查询") String region,
                                  @RequestParam(value = "page",required = true) Integer page,@RequestParam(value = "pageSize",required = false) Integer pageSize) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                OperateUserInfoDto userDto = JsonXMLUtils.json2obj(redisUtil.getValue(cloudAuthToken+userId),OperateUserInfoDto.class);
                if (!userDto.getRoleType().equals(RoleTypeEnum.CREATOR.getCode())) {
                    return Result.failure(USER_NO_AUTHORITY,userNoAuthority);
                }
                Map<String, Object> operateUserInfoDtoList = operateUserService.fineOperateUser(page,pageSize,userId,name,region);
                return Result.ok().setData(operateUserInfoDtoList);
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 查询角色
     *
     * @param
     * @return
     */
    @PostMapping(value = "findRole",produces="application/json")
    @ApiOperation(value = "查询角色")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result findRole(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                return Result.ok().setData(rolesService.queryAll(new Roles()));
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 用户标准注册
     *
     * @param
     * @return
     */
    @PostMapping(value = "updateInfo",produces="application/json")
    @ApiOperation(value = "修改个人信息")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result updateInfo(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                             @RequestBody OperateUserInfoDto manageInfoDto) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                OperateInfo operateUserInfo = ModelMapperUtil.strictMap(manageInfoDto, OperateInfo.class);
                operateUserInfo.setId(userId);
                operateUserService.update(operateUserInfo);
                redisUtil.setValue(cloudAuthToken+userId, JsonXMLUtils.obj2json(operateUserInfo)); // 存入缓存
                return Result.ok();
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 查询个人信息
     *
     * @param
     * @return
     */
    @GetMapping(value = "findUserInfo",produces="application/json")
    @ApiOperation(value = "查询个人信息")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result findUserInfo(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                OperateInfo operateInfo = operateUserService.queryById(userId);
                OperateUserInfoDto operateUserInfoDto = ModelMapperUtil.strictMap(operateInfo, OperateUserInfoDto.class);
                operateUserInfoDto.setOPassword("***********");
                return Result.ok().setData(operateUserInfoDto);
            }
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
        return Result.failure(USERNAME_REPEAT,"用户名已存在，请重新输入");
    }
    /**
     * 清除缓存
     * @param strings
     * @param redisUtil
     */
    public static void clearCache(Set<String> strings, RedisUtil redisUtil) {
        strings.forEach(
                s -> {
                    String value = redisUtil.getValue(s);
                    try {
                        OperateUserInfoDto userDto1 = JsonXMLUtils.json2obj(value, OperateUserInfoDto.class);
                        redisUtil.leftPush(USER_INFO_AI_FISH,JsonXMLUtils.obj2json(userDto1));
                        redisUtil.delete(s);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );
    }
    /**
     * 用户注册
     * @param
     * @return
     */
    @PostMapping(value = "register",produces="application/json")
    @ApiOperation(value = "注册")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.INSERT,operatorType = OperatorType.MANAGE)
    public Result register(@RequestBody LoginUserDto loginUserDto) throws Exception {
        if (StringUtils.isNotEmpty(loginUserDto.getAccount()) && StringUtils.isNotEmpty(loginUserDto.getPassword())) {
            OperateInfo operateInfo = new OperateInfo();
            operateInfo.setId(IdUtil.getStringId());
            operateInfo.setOperateName(loginUserDto.getAccount());
            operateInfo.setOPassword(loginUserDto.getPassword());
            operateInfo.setAddTime(new Date());
            operateInfo.setRegion(loginUserDto.getRegion());
            operateInfo.setRoleId("2");
            operateInfo.setRoleType(2);
            operateInfo.setRoleDesc("admin");
            operateInfo.setOperateId("292498415457281");
            operateUserService.insert(operateInfo);
            Map map = new HashMap(16);
            String token = UserTokenManager.generateToken(operateInfo.getId());
            redisUtil.setValue(token+operateInfo.getId(), JsonXMLUtils.obj2json(operateInfo)); // 存入缓存
            map.put("Token",token);
            map.put("type",operateInfo.getRoleType());
            return Result.ok().setData(map);
        }
        return Result.failure(USERNAME_OR_NOTFOUND,usernameOrNotFound);
    }
    /**
     * 用户注销
     * @param
     * @return
     */
    @GetMapping(value = "loginOut",produces="application/json")
    @ApiOperation(value = "用户注销")
    @ResponseBody
    @Log(isSaveRequestData = true,businessType = BusinessType.QUERY,operatorType = OperatorType.MANAGE)
    public Result loginOut(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken) throws Exception {
        System.out.println(cloudAuthToken);
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 缓存是否存在
                String value = redisUtil.getValue(cloudAuthToken + userId);
                OperateUserInfoDto userDto = JsonXMLUtils.json2obj(value, OperateUserInfoDto.class);
                OperateInfo userInfo = new OperateInfo();
                redisUtil.leftPush(USER_INFO_AI_FISH,JsonXMLUtils.obj2json(userDto));
                redisUtil.delete(cloudAuthToken+userId);
                return Result.ok();
            }
            return Result.failure(USERNAME_Off_SITE,"请返回首页重新登录");
        }
        return Result.failure(USER_NOT_LOGIN,"用户未登录");
    }
}
